import React, { useEffect } from "react";
import {Modal, Form, Input, Select, message} from "antd";
import {UserApi} from '@/api/index'

const { Option } = Select;

export default function EditUserModal({ visible, onCancel, onSuccess, userId }) {
    const [form] = Form.useForm()
    const [loading, setLoading] = React.useState(false)
    const [userData, setUserData] = React.useState(null)
    const [dataLoading, setDataLoading] = React.useState(false)

    // 当弹层打开且有用户ID时，获取用户详情
    useEffect(() => {
        if (visible && userId) {
            getUserDetail()
        }
    }, [visible, userId])

    const getUserDetail = async () => {
        try {
            setDataLoading(true)
            const ret = await UserApi.getDetail({ id: userId })
            if (ret && ret.code === 200) {
                const userInfo = ret.data
                setUserData(userInfo)
                form.setFieldsValue({
                    username: userInfo.username,
                    realName: userInfo.realName,
                    email: userInfo.email,
                    status: userInfo.status,
                    remark: userInfo.remark
                })
            } else {
                message.error(ret.message || '获取用户信息失败')
            }
        } catch (error) {
            message.error('获取用户信息失败')
        } finally {
            setDataLoading(false)
        }
    }

    const handleSubmit = async () => {
        try {
            const values = await form.validateFields()
            setLoading(true)
            
            // 添加用户ID到更新参数中
            const updateData = {
                ...values,
                id: userId
            }
            
            const ret = await UserApi.update(updateData)
            if (ret && ret.code === 200) {
                message.success('用户更新成功！')
                form.resetFields()
                onSuccess() // 调用父组件的成功回调
            } else {
                message.error(ret.message || '更新失败')
            }
        } catch (error) {
            message.error('请检查表单信息')
        } finally {
            setLoading(false)
        }
    }

    const handleCancel = () => {
        form.resetFields()
        setUserData(null)
        onCancel()
    }

    return (
        <Modal
            title="编辑用户"
            open={visible}
            onOk={handleSubmit}
            onCancel={handleCancel}
            confirmLoading={loading || dataLoading}
            width={600}
        >
            <Form
                form={form}
                layout="vertical"
                name="editUserForm"
            >
                <Form.Item
                    label="用户名"
                    name="username"
                    rules={[
                        { required: true, message: '请输入用户名！' },
                        { min: 3, max: 20, message: '用户名长度为3-20个字符！' }
                    ]}
                >
                    <Input placeholder="请输入用户名" allowClear />
                </Form.Item>

                <Form.Item
                    label="姓名"
                    name="realName"
                    rules={[
                        { required: true, message: '请输入姓名！' },
                        { max: 50, message: '姓名不能超过50个字符！' }
                    ]}
                >
                    <Input placeholder="请输入真实姓名" allowClear />
                </Form.Item>

                <Form.Item
                    label="邮箱"
                    name="email"
                    rules={[
                        { required: true, message: '请输入邮箱地址！' },
                        { type: 'email', message: '请输入有效的邮箱地址！' }
                    ]}
                >
                    <Input placeholder="请输入邮箱地址" allowClear />
                </Form.Item>

                <Form.Item
                    label="状态"
                    name="status"
                    rules={[{ required: true, message: '请选择用户状态！' }]}
                >
                    <Select placeholder="请选择用户状态">
                        <Option value={1}>正常</Option>
                        <Option value={0}>禁用</Option>
                    </Select>
                </Form.Item>

                <Form.Item
                    label="备注"
                    name="remark"
                >
                    <Input.TextArea rows={3} placeholder="请输入备注信息（可选）" allowClear />
                </Form.Item>
            </Form>
        </Modal>
    )
} 